package com.artron.mediaartron.ui.fragment.order;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.IntDef;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.alipay.sdk.app.PayTask;
import com.artron.baselib.adapter.recyclerview.BaseViewHolder;
import com.artron.baselib.base.BaseLoadingFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.image.ImageUtils;
import com.artron.baselib.utils.ToastUtil;
import com.artron.baselib.utils.UIUtils;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.callback.PayCallback;
import com.artron.mediaartron.data.entity.AliPayResult;
import com.artron.mediaartron.data.entity.OrderDetailData;
import com.artron.mediaartron.data.entity.WeChatData;
import com.artron.mediaartron.data.event.FinishEvent;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.data.production.FrameConstant;
import com.artron.mediaartron.data.production.SuitableSizeHelper;
import com.artron.mediaartron.ui.fragment.dialog.NormalDialogFragment;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static com.artron.baselib.utils.UIUtils.ColorText.holder;
import static com.artron.baselib.utils.UIUtils.getColor;

/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-10-30.
 */

public class OrderDetailFragment extends BaseLoadingFragment<OrderDetailData> implements View.OnClickListener {

    @BindView(R.id.OrderDetailFragment_tv_price_type)
    protected TextView mTvPriceType;
    @BindView(R.id.OrderDetailFragment_tv_price)
    protected TextView mTvPrice;
    @BindView(R.id.OrderDetailFragment_tv_name)
    protected TextView mTvName;
    @BindView(R.id.OrderDetailFragment_tv_tel_num)
    protected TextView mTvTelNum;
    @BindView(R.id.OrderDetailFragment_tv_address)
    protected TextView mTvAddress;
    @BindView(R.id.OrderDetailFragment_fl_favourable)
    protected FrameLayout mFlFavourable;
    @BindView(R.id.OrderDetailFragment_ll_content)
    protected LinearLayout mLlContent;
    @BindView(R.id.OrderDetailFragment_tb_zhifubao)
    protected ToggleButton mTbZhifubao;
    @BindView(R.id.OrderDetailFragment_ll_zhifubao)
    protected LinearLayout mLlZhifubao;
    @BindView(R.id.OrderDetailFragment_tb_weixin)
    protected ToggleButton mTbWeixin;
    @BindView(R.id.OrderDetailFragment_ll_weixin)
    protected LinearLayout mLlWeixin;
    @BindView(R.id.OrderDetailFragment_tv_invoice)
    protected TextView mTvInvoce;
    @BindView(R.id.OrderDetailFragment_tv_code)
    protected TextView mTvCode;
    @BindView(R.id.OrderDetailFragment_tv_copy)
    protected TextView mTvCopy;
    @BindView(R.id.OrderDetailFragment_tv_date)
    protected TextView mTvDate;
    @BindView(R.id.OrderDetailFragment_tv_all_price)
    protected TextView mTvAllPrice;
    @BindView(R.id.OrderDetailFragment_tv_final_price)
    protected TextView mTvFinalPrice;
    @BindView(R.id.OrderDetailFragment_btn_cancel)
    protected Button mBtnCancel;
    @BindView(R.id.OrderDetailFragment_btn_pay)
    protected Button mBtnPay;
    @BindView(R.id.OrderDetailFragment_btn_delete)
    protected Button mBtnDelete;
    private String mOrderId;
    private OrderDetailData mData;

    @Retention(RetentionPolicy.SOURCE)
    @IntDef({NOT_PAY, PAY_MAKE, CANCEL, PAY_FINISH})
    public @interface PayModel {
    }

    public static final int NOT_PAY = 1000;
    public static final int PAY_MAKE = 1001;
    public static final int CANCEL = 1002;
    public static final int PAY_FINISH = 1004;


    public static OrderDetailFragment newInstance(String orderId) {
        OrderDetailFragment fragment = new OrderDetailFragment();
        fragment.init(orderId);
        return fragment;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        show();
    }

    private void init(String orderId) {
        this.mOrderId = orderId;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_order_detail;
    }

    @PayModel
    private int getType(int status) {
        if (status == 1) {
            return NOT_PAY;
        } else if (status == -1) {
            return CANCEL;
        } else if (status >= 2 && status < 10) {
            return PAY_MAKE;
        } else {
            return PAY_FINISH;
        }
    }

    @Override
    public void initViewWithData(OrderDetailData data) {
        this.mData = data;

        int type = getType(data.getStatus());
        String totalPriceText = "需付款：";
        switch (type) {
            case CANCEL:
                mTvPrice.setVisibility(View.INVISIBLE);
                mTvPriceType.setText("已取消");
                mTvPriceType.setCompoundDrawablesWithIntrinsicBounds(UIUtils.getDrawable(R.drawable.ic_order_cancel),
                        null, null, null);
                mBtnPay.setVisibility(View.GONE);
                mBtnCancel.setVisibility(View.GONE);
                totalPriceText = "实付款：";
                break;
            case NOT_PAY:
                mTvPrice.setText("需付款：￥" + data.getTotalPrice());
                mTvPriceType.setText("等待付款");
                mTvPriceType.setCompoundDrawablesWithIntrinsicBounds(UIUtils.getDrawable(R.drawable.ic_order_wait),
                        null, null, null);
                mBtnDelete.setVisibility(View.GONE);
                break;
            case PAY_MAKE:
            case PAY_FINISH:
                mTvPrice.setText("物流信息");
                mTvPriceType.setText("已付款");
                mTvPriceType.setCompoundDrawablesWithIntrinsicBounds(UIUtils.getDrawable(R.drawable.ic_order_pay),
                        null, null, null);
                OrderDetailData.PaymentBean payment = mData.getPayment();
                if ("wechat".equals(payment.getType())) {
                    mLlZhifubao.setVisibility(View.GONE);
                    mTbZhifubao.setChecked(true);
                } else if ("alipay".equals(payment.getType())) {
                    mLlWeixin.setVisibility(View.GONE);
                    mTbWeixin.setChecked(true);
                }
                mBtnPay.setVisibility(View.GONE);
                mBtnCancel.setVisibility(View.GONE);
                mBtnDelete.setVisibility(View.GONE);
                totalPriceText = "实付款：";
                break;
        }

        //地址赋值
        mTvName.setText(data.getConsigneeName());
        mTvTelNum.setText(data.getConsigneeMobileCode());
        mTvAddress.setText(data.getConsigneeDetailAddress());

        //初始化框画图片数据
        initFrameImage();

        mFlFavourable.setVisibility(View.GONE);

        //微信支付宝按钮点击事件
        mLlWeixin.setOnClickListener(this);
        mLlZhifubao.setOnClickListener(this);
        mTbWeixin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (mTbZhifubao.isChecked() && isChecked) {
                    mTbZhifubao.setChecked(false);
                }
                if (!mTbZhifubao.isChecked() && !isChecked) {
                    mTbWeixin.setChecked(true);
                }
            }
        });

        mTbZhifubao.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (mTbWeixin.isChecked() && isChecked) {
                    mTbWeixin.setChecked(false);
                }
                if (!mTbWeixin.isChecked() && !isChecked) {
                    mTbZhifubao.setChecked(true);
                }
            }
        });

        //其他
        if (data.getInvoice() != null) {
            mTvInvoce.setText(data.getInvoice().getTitle());
        }
        mTvCopy.setOnClickListener(this);
        mTvAllPrice.setText("￥" + data.getTotalPrice());
        UIUtils.setTextWithColor(mTvFinalPrice,
                holder(getColor(R.color.gray_99), totalPriceText),
                holder(getColor(R.color.order_purple),
                        String.format("￥%d.00", data.getTotalPrice())));

        mBtnCancel.setOnClickListener(this);
        mBtnPay.setOnClickListener(this);
        mBtnDelete.setOnClickListener(this);
//        ThrottleFirstClickHelper.throttleFirst(mBtnPay, this);

        mTvCode.setText("订单号：" + data.getOrderCode());
        mTvDate.setText("下单时间：" + data.getCreateDate());
    }

    @Override
    protected Observable<Response<OrderDetailData>> retrofitData() {
        return RetrofitHelper.getOrderApi().queryOrder(mOrderId);
    }

    /**
     * 绑定中间框画图片相关数据
     */
    private void initFrameImage() {
        List<OrderDetailData.WorksListBean> worksList = mData.getWorksList();
        for (OrderDetailData.WorksListBean item : worksList) {
            BaseViewHolder holder = BaseViewHolder.createViewHolder(mContext, mLlContent,
                    R.layout.layout_order_detail);
            FrameLayout flFrame = holder.getView(R.id.OrderDetailFragment_fl_frame);
            ImageView ivImage = holder.getView(R.id.OrderDetailFragment_iv_image);
            String[] sizeArr = item.getWorksSize().split("X");
            float width = Float.parseFloat(sizeArr[0]);
            float height = Float.parseFloat(sizeArr[1]);
            initImageWidthAndHeight(flFrame, ivImage, width, height);
            ImageUtils.setUrl(ivImage, item.getThumbnailPath());

            String type = "框画";
            if ("haibao".equals(item.getWorksTypeCode())) {
                type = "海报";
            }

            holder.setText(R.id.OrderDetailFragment_tv_image_name, item.getWorksName())
                    .setText(R.id.OrderDetailFragment_tv_image_type, type)
                    .setText(R.id.OrderDetailFragment_tv_image_frame_name, item.getWorksShape())
                    .setText(R.id.OrderDetailFragment_tv_image_size, item.getWorksSize() + "mm")
                    .setText(R.id.OrderDetailFragment_tv_image_number, "X" + item.getWorksQuantity())
                    .setText(R.id.OrderDetailFragment_tv_image_price, "￥" + item.getWorksPrice());
            mLlContent.addView(holder.getContentView());
        }
    }


    private void initImageWidthAndHeight(View ivFrame, ImageView ivImage, float width, float height) {
        ViewGroup.LayoutParams frameParams = ivFrame.getLayoutParams();

        int heightSpec = View.MeasureSpec.makeMeasureSpec(frameParams.height,
                View.MeasureSpec.EXACTLY);
        int widthSpec = View.MeasureSpec.makeMeasureSpec(frameParams.width,
                View.MeasureSpec.EXACTLY);
        ivFrame.measure(widthSpec, heightSpec);

        float frameWidth = ivFrame.getMeasuredWidth();

        float per = frameWidth / Math.max(width, height);

        ViewGroup.LayoutParams imageParams = ivImage.getLayoutParams();
        imageParams.height = (int) ((height - FrameConstant.BLANK_CUSTOM_MADE) * per);
        imageParams.width = (int) ((width - FrameConstant.BLANK_CUSTOM_MADE) * per);
        ivImage.setLayoutParams(imageParams);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.OrderDetailFragment_ll_weixin:
                mTbWeixin.setChecked(true);
                break;
            case R.id.OrderDetailFragment_ll_zhifubao:
                mTbZhifubao.setChecked(true);
                break;
            case R.id.OrderDetailFragment_tv_copy:
                ClipboardManager manager = (ClipboardManager)
                        mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newPlainText("订单号", mData.getOrderCode());
                manager.setPrimaryClip(clipData);
                ToastUtil.show("复制成功");
                break;
            case R.id.OrderDetailFragment_btn_cancel:
                NormalDialogFragment dialog1 = NormalDialogFragment.newInstance("确认要取消订单吗？取消后订单将会失效",
                        "再想想", "确定");
                dialog1.setOnNegativeClickListener(new Action0() {
                    @Override
                    public void call() {
                        RetrofitHelper.subscript(RetrofitHelper.getOrderApi().cancelOrder(mData.getOrderCode()),
                                new Action1<Response>() {
                                    @Override
                                    public void call(Response response) {
                                        Log.d(TAG, "call: " + response);
                                    }
                                });
                        getActivity().onBackPressed();
                    }
                });
                dialog1.show(getChildFragmentManager(), dialog1.getOurTag());
                break;
            case R.id.OrderDetailFragment_btn_pay:
                ensurePay();
                break;
            case R.id.OrderDetailFragment_btn_delete:
                NormalDialogFragment dialog2 = NormalDialogFragment.newInstance(
                        "确认要刪除订单吗？取消后订单将会失效", "再想想", "确定");
                dialog2.setOnNegativeClickListener(new Action0() {
                    @Override
                    public void call() {
                        RetrofitHelper.subscript(RetrofitHelper.getOrderApi()
                                        .recycleOrder(mData.getOrderCode()),
                                new Action1<Response>() {
                                    @Override
                                    public void call(Response response) {
                                        Log.d(TAG, "call: " + response);
                                    }
                                });
                        getActivity().onBackPressed();
                    }
                });
                dialog2.show(getChildFragmentManager(), dialog2.getOurTag());
                break;
        }
    }

    private Observable<Response<WeChatData>> getPayApi() {
        if (mTbZhifubao.isChecked()) {
            return RetrofitHelper.getHostApi().getAlipayData(mData.getOrderCode(), mData.getTotalPrice() + "", "传媒雅昌")
                    .map(new Func1<Response<String>, Response<WeChatData>>() {
                        @Override
                        public Response<WeChatData> call(Response<String> response) {
                            Response<WeChatData> result = new Response<>();
                            WeChatData data = new WeChatData();
                            data.setAlipayStr(response.getData());
                            result.setData(data);
                            return result;
                        }
                    });
        } else {
            SuitableSizeHelper.getHelper().setOrderId(mData.getOrderId());
            return RetrofitHelper.getHostApi().getWeChatData(mData.getOrderCode(), mData.getTotalPrice() + "");
        }
    }

    private void ensurePay() {
        getPayApi()
                .flatMap(new Func1<Response<WeChatData>, Observable<AliPayResult>>() {
                    @Override
                    public Observable<AliPayResult> call(Response<WeChatData> response) {
                        if (response == null || response.getData() == null) {
                            return null;
                        }

                        final WeChatData data = response.getData();
                        if (mTbZhifubao.isChecked()) {
                            return Observable.create(new Observable.OnSubscribe<AliPayResult>() {
                                @Override
                                public void call(Subscriber<? super AliPayResult> subscriber) {
                                    try {
                                        PayTask aliPay = new PayTask(getActivity());
                                        String aliPayStr = data.getAlipayStr();
                                        Map<String, String> result = aliPay.payV2(aliPayStr, true);
                                        subscriber.onNext(new AliPayResult(result));
                                    } catch (Exception e) {
                                        MobclickAgent.reportError(UIUtils.getContext(), e);
                                        subscriber.onError(e);
                                    } finally {
                                        subscriber.onCompleted();
                                    }
                                }
                            });
                        } else {
                            SuitableSizeHelper.getHelper().setStartPayDetail(false);
                            SuitableSizeHelper.getHelper().setNotStart(false);
                            IWXAPI wxApi = WXAPIFactory.createWXAPI(mContext, null);
                            wxApi.registerApp(data.getAppid());
                            PayReq request = new PayReq();
                            request.appId = data.getAppid();
                            request.partnerId = data.getMch_id();
                            request.prepayId = data.getPrepay_id();
                            request.packageValue = data.getPackageX();
                            request.nonceStr = data.getNonce_str();
                            request.timeStamp = data.getTimestamp() + "";
                            request.sign = data.getSecondSignature();
                            wxApi.sendReq(request);
                        }
                        return null;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Action1<AliPayResult>() {
                    @Override
                    public void call(AliPayResult result) {
                        if (result != null) {
                            if (result.getResult() != null
                                    && "9000".equals(result.getResultStatus())) {
                                PayCallback.startFinishPage(getActivity(), mData.getOrderId(), true, false, true);
                            } else {
                                ToastUtil.show("支付失败");
                            }
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        MobclickAgent.reportError(mContext, throwable);
                    }
                });
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    @Subscribe
    public void onFinishEvent(FinishEvent finishEvent) {
        if (finishEvent.isFinish()) {
            getActivity().finish();
        }
    }
}
